package com.wtgroup.demo.common.bean;

/**
 * LeetCode 专用 ListNode 变体
 * Definition for singly-linked list.
 * 增加了一些好用方法
 */
 public class LinkNode {
     // public long id;
     public int value;
     public LinkNode next;
     public LinkNode() {}
     public LinkNode(int value) { this.value = value; }
     public LinkNode(int value, LinkNode next) { this.value = value; this.next = next; }

    public String toString() {
         return value +"";
    }

    public void print() {
         LinkNode.print(this);
    }

     // int[] --> ListNode
    public static LinkNode toListNode(int ... arr) {
        if (arr==null || arr.length==0) {
            return null;
        }

        LinkNode head = new LinkNode(arr[0]);
        LinkNode tail = head;
        for (int i = 1; i < arr.length; i++) {
            tail.next = new LinkNode(arr[i]);
            tail = tail.next;
        }

        return head;
    }

    public static void print(LinkNode head) {
        System.out.println(head.prettyString());
    }

    public String prettyString() {
        StringBuilder sb = new StringBuilder();
        String sep = "->";
        int count = 0;
        LinkNode curr = this;
        while (curr != null && count < Integer.MAX_VALUE) { // 防止环
            sb.append(curr.value).append(sep);
            curr = curr.next;
            count++;
        }
        sb.delete(Math.max(0, sb.length() - sep.length()), sb.length());
        // 10, 1->2->3
        return count + ", " + sb;
    }
}
